<?php
namespace App\Repositories\System;

use App\Exceptions\OrdinaryException;
use App\Models\Model;
use App\Repositories\BaseRepository;
use App\Models\Message\Messages;

class MessageRepository extends BaseRepository{

    public function model()
    {
        // TODO: Implement model() method.
        return Messages::class;
    }

    /**
     * 获取用户消息列表
     *
     * @param int $uid 用户id
     * @param int $page 页数
     * @param int $limit 条目数
     * @author zx
     * @date 2019-01-18
     * @return Mixed
     */
    public function getMessageList(int $uid, array $columns=['*'], int $page=0, int $limit=15)
    {
        $models = $this->where("uid", $uid)
            ->where("is_delete", 0)
            ->paginate($limit, $columns, 'page', $page);
        return $models;
    }

    /**
     * 获取系统信息详情
     *
     * @param int $id 详情id
     * @author zx
     * @date 2019-01-19
     * @return Model
     */
    public function getMessageDetail(int $id)
    {
        $detail = $this->where("id", $id)->first();
        if($detail->status == 0){
            $this->updateByPrimary($detail->id, ['status' => 1]);
        }
        return $detail;
    }

    /**
     * 一键标记已读
     *
     * @param int $uid 用户ID
     * @author zx
     * @date 2019-01-20
     * @return NOT
     */
    public function markedRead(int $uid)
    {
        $lists = $this->where("uid", $uid)
            ->where("status", 0)
            ->where("is_delete", 0)
            ->get();
        if($lists->isNotEmpty()){
            foreach($lists as $key => $val){
                $this->updateByPrimary($val->id, ['status' => 1]);
            }
        }
    }

    /**
     * 发送消息
     *
     * @param int $uid 接收人ID
     * @param string $title 标题
     * @param string $content 内容
     * @param int $type 消息类型
     * @param int $sid 发送者ID
     * @author zx
     * @date 2019-01-16
     * @return boolean
     */
    public function addMessages( int $uid=0, string $title='', string $content='', int $type=0, int $sid=1 )
    {
        if ( ! $uid || ! $title || ! $content || ! $sid ) return resultSet(500, '参数错误');
        $res = FALSE;
        $data = [];
        $data['aid'] = $sid;
        $data['uid'] = $uid;
        $data['title'] = $title;
        $data['type'] = $type;
        $data['content'] = $content;
        $res = $this->create($data);
        if (isset($res->id) && $res->id) {
            $res = TRUE;
        }
        return $res;
    }

    public function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }

}